//
//  ConfirmPayVC.m
//  sensen_ios
//
//  Created by pro on 16/2/29.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ConfirmPayVC.h"

#import "OrderPayRequestHandle.h" // 支付
#import "WXPayRequestHandle.h"

// 控制器
#import "ShopCartVC.h" // 购物车
#import "ShopVC.h"
#import "OrderTotalVC.h"
#import "ShopSectionsVC.h"
// 单元格
#import "PayStyleCell.h" // 支付方式单元格

@interface ConfirmPayVC () <UITableViewDelegate, UITableViewDataSource>
{
    UITableView *_tableView; // 表视图
    UIButton *_confirmButton; // 确认按钮
    
    int _payStyle; // 1:微信支付 2:支付宝支付
}
@end

@implementation ConfirmPayVC
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _payStyle = 1;
    
    self.title = @"支付方式";
    self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    
    [self createLeftBarButtonItemWithImagename:nil]; // 创建左侧返回按钮
    
    [self _createViews]; // 创建视图
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weixinPaySuccess) name:@"weixinPaySuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weixinPayFailure) name:@"weixinPayfailure" object:nil];

    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    // 设置背景颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];
    
    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.navigationController.tabBarController;
    [main hideTabBar];
}
- (void)viewWillDisappear:(BOOL)animated {
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.navigationController.tabBarController;
    [main showTabBar];
}


#pragma mark - 创建视图
- (void)_createViews {
    
    [self _initTableView]; // 创建表视图
    [self _createConfirmButton]; // 创建确认按钮
}
// 创建表视图
- (void)_initTableView {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    _tableView.scrollEnabled = NO;
    
    // 设置表视图的高度
    _tableView.height = 50 * 3 + 20;
    
    // 注册单元格
    [_tableView registerClass:[PayStyleCell class] forCellReuseIdentifier:@"PayStyleCell"];
}
// 创建确认按钮
- (void)_createConfirmButton {
    
    _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _confirmButton.frame = CGRectMake(20, _tableView.bottom + 40, (SCREEN_WIDTH - 20 * 2), 44);
    _confirmButton.backgroundColor = SS_NAVI_ORANGE_COLOR;
    [_confirmButton setTitle:@"去支付" forState:UIControlStateNormal];
    [_confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_confirmButton addTarget:self action:@selector(_confirmAction:) forControlEvents:UIControlEventTouchUpInside];
    _confirmButton.layer.cornerRadius = 6;
    [self.view addSubview:_confirmButton];
}

#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    // 第一行，显示总价
    if (indexPath.row == 0) {
        UITableViewCell *normalCell = [tableView dequeueReusableCellWithIdentifier:@"normalCell"];
        if (normalCell == nil) {
            normalCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"normalCell"];
            normalCell.selectionStyle = UITableViewCellSelectionStyleNone;
            normalCell.textLabel.textColor = [UIColor darkGrayColor];
            normalCell.textLabel.font = FONT(15);
            
            normalCell.detailTextLabel.textColor = SS_NAVI_ORANGE_LIGHT_COLOR;
            normalCell.detailTextLabel.font = FONT(15);
        }
        normalCell.textLabel.text = @"使用第三方平台支付";
        normalCell.detailTextLabel.text = [NSString stringWithFormat:@"￥%.2f", [_payOrderModel.total_price floatValue]];
        return normalCell;
    }
    // 第二行开始显示支付方式
    else {
        PayStyleCell *payStyleCell = (PayStyleCell *)[tableView dequeueReusableCellWithIdentifier:@"PayStyleCell"];
        // 微信支付
        if (indexPath.row == 1) {
            payStyleCell.iconView.image = [UIImage imageNamed:@"付款详情_微信支付"];
            payStyleCell.titleLabel.text = @"微信支付";
            payStyleCell.selectButton.selected = YES;
        }
        // 支付宝支付
        else if (indexPath.row == 2) {
            payStyleCell.iconView.image = [UIImage imageNamed:@"付款详情_支付宝"];
            payStyleCell.titleLabel.text = @"支付宝";
            payStyleCell.selectButton.selected = NO;
        }
        return payStyleCell;
    }
        
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 1;
}
// 设置组尾高
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5;
}
// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    // 点击微信支付单元格，显示“当前不提供该支付方式”字样
//    if (indexPath.row == 1) {
//        [SVProgressHUD showOnlyStatus:@"当前不提供该支付方式" withDuration:3];
//    }
    
    _payStyle = (int)indexPath.row;
    
    for (int i = 1; i < 3; i ++) {
        
        NSIndexPath *paht = [NSIndexPath indexPathForRow:i inSection:0];
        PayStyleCell *cell = [tableView cellForRowAtIndexPath:paht];
        
        if (paht.row == indexPath.row) {
            cell.selectButton.selected = YES;
            
        } else {
            cell.selectButton.selected = NO;
        }

    }
}


#pragma mark - 点击事件
- (void)leftAction:(UIButton *)button {
    // 确认订单里如果返回则直接返回到购物车页面
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[ShopCartVC class]]) {
            [self.navigationController popToViewController:vc animated:YES];
            return;
        }
    }
    
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[ShopSectionsVC class]]) {
            [self.navigationController popToViewController:vc animated:YES];
            return;
        }
    }
    
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[ShopVC class]]) {
            [self.navigationController popToViewController:vc animated:YES];
            return;
        }
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
// 确认按钮点击事件
- (void)_confirmAction:(UIButton *)button {
    
    if (_payStyle == 1) {
        [self wxPay];
    } else if (_payStyle == 2) {
        [self aliPay];
    }
    
}

#pragma mark - 支付方式
// 支付宝支付
- (void)aliPay {
    
    // 对订单进行校验，校验不合法则不予购买
    if (![self.payOrderModel isLegal]) {
        [SVProgressHUD showErrorWithStatus:@"支付有风险,请重新购买" withDuration:2];
        return;
    }
    
//        if (DEBUG) {
//            self.payOrderModel.total_price = @"0.02";
    //    }
    
    AliPayModel *payModel = [AliPayModel defaultPayModel];
    payModel.tradeNO = self.payOrderModel.code;
    payModel.productName = self.payOrderModel.name;
    payModel.productDescription = self.payOrderModel.desc;
    payModel.totalFee = self.payOrderModel.total_price;
    payModel.showUrl = self.payOrderModel.show_url;
    if ([payModel.totalFee integerValue] <= 0 ) {
        payModel.totalFee = @"0.01";
    }
    
    [OrderPayRequestHandle requestPayModel:payModel success:^(NSDictionary *dic) {
        OrderTotalVC *vc = [[OrderTotalVC alloc] init];
        vc.intFirstSelect = 2;
        [self.navigationController pushViewController:vc animated:YES];
    } error:^(NSString *error) {
        OrderTotalVC *vc = [[OrderTotalVC alloc] init];
        vc.intFirstSelect = 1;
        [self.navigationController pushViewController:vc animated:YES];
    }];

}
// 微信支付
- (void)wxPay {
    
    [SVProgressHUD showWithStatus:@"正在为您打开微信..."];
    if ([self.payOrderModel.total_price integerValue] <= 0 ) {
        self.payOrderModel.total_price = @"0.01";
    }

    
    [BoyeHttpClient post:@"BY_Wxpay_preOrder" apiVerson:100 params:@{@"code":self.payOrderModel.code, @"desc":self.payOrderModel.desc , @"total_price":self.payOrderModel.total_price} success:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"微信:%@", result);
        
        [SVProgressHUD dismiss];
        
        PayReq *request = [[PayReq alloc] init];
        request.partnerId = result[@"partnerid"];
        request.prepayId= result[@"prepayid"];
        request.package = result[@"package"];
        request.nonceStr= result[@"noncestr"];
        request.timeStamp = [result[@"timestamp"] intValue];
        request.sign = result[@"sign"];
        
        [WXApi sendReq:request];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];
    }];

}

- (void)weixinPaySuccess {
    [SVProgressHUD showSuccessWithStatus:@"支付成功" withDuration:2.5];
    OrderTotalVC *vc = [[OrderTotalVC alloc] init];
    vc.intFirstSelect = 2;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)weixinPayFailure {
    [SVProgressHUD showErrorWithStatus:@"支付失败" withDuration:2.5];
    OrderTotalVC *vc = [[OrderTotalVC alloc] init];
    vc.intFirstSelect = 1;
    [self.navigationController pushViewController:vc animated:YES];

}
#pragma makr -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
